package com.qf.shop.dao.Impl;

import com.qf.shop.dao.CartDao;
import com.qf.shop.entity.Cart;
import com.qf.shop.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

;

public class CartDaoImpl implements CartDao {
    private QueryRunner queryRunner = new QueryRunner();

    @Override
    public Cart existsCart(int id, int gid) {

        try {
            return queryRunner.query(DruidUtils.getConnection(), "select * from cart where id = ? and gid = ?;", new BeanHandler<>(Cart.class),id,gid);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public int updateCart(Cart cart) {
        try {
            return queryRunner.update(DruidUtils.getConnection(), "update cart set num = ? ,money = ? where id = ? and gid = ?;",cart.getNum(),cart.getMoney(),cart.getId(),cart.getGid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int insertCart(Cart carts) {
        try {
            return queryRunner.update(DruidUtils.getConnection(),"insert into cart values(?,?,?,?);",carts.getId(),carts.getGid(),carts.getNum(),carts.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public List<Cart> selectById(int id) {
        try {
            return queryRunner.query(DruidUtils.getConnection(),"select * from cart where id = ?;",new BeanListHandler<>(Cart.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public int deleteCart(int gid) {
        try {
            return queryRunner.update(DruidUtils.getConnection(),"delete from cart where gid = ?;",gid);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public int deleteById(int id) {
        try {
            return queryRunner.update(DruidUtils.getConnection(),"delete from cart where id =?;",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
